//
//  AddGonggaoViewController.m
//  YiqiMobile
//
//  Created by henry on 13-3-30.
//  Copyright (c) 2013年 henry. All rights reserved.
//

#import "AddGonggaoViewController.h"
#import "QuartzCore/QuartzCore.h"
#import "Config.h"
#import "Utility.h"
#import "AppDelegate.h"
#import "JSON.h"
#import "DefineAction.h"
#import "MBProgressHUD.h"

@interface AddGonggaoViewController ()

@end

@implementation AddGonggaoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.titleView=[Utility getTitleView:@"供稿内容"];
    self.view.backgroundColor=[UIColor colorWithRed:249.0/255 green:249.0/255 blue:249.0/255 alpha:1.0];
    /*[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    */
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithCustomView:[Utility customButton:self action:@selector(navButtonActon:) normalImage:@"gonggao_logout_normal.png"  lightedImage:@"gonggao_logout_hover.png" frame:CGRectMake(0, 0, 59, 29) title:nil tag:NAVGGBUTTONTAG+1]];
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithCustomView:[Utility customButton:self action:@selector(navButtonActon:) normalImage:@"gonggao_send_normal.png" lightedImage:@"gonggao_send_hover.png" frame:CGRectMake(0, 0, 59, 29) title:nil tag:NAVGGBUTTONTAG+2]];
    
    
    
    
    /*self.accessoryView=[[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    self.accessoryView.barStyle=UIBarStyleBlackOpaque;
   
    UIButton *barbutton1=[Utility customButton:self action:@selector(tappedToolButton:) normalImage:@"gonggao_face.png" lightedImage:@"gonggao_face.png" frame:CGRectMake(20, 8, 29, 29) title:nil tag:TOOLGGBUTTONTAG+1];
    UIButton *barbutton2=[Utility customButton:self action:@selector(tappedToolButton:) normalImage:@"gonggao_face.png" lightedImage:@"gonggao_face.png" frame:CGRectMake(80, 8, 29, 29) title:nil tag:TOOLGGBUTTONTAG+2];
    UIButton *barbutton3=[Utility customButton:self action:@selector(tappedToolButton:) normalImage:@"gonggao_face.png" lightedImage:@"gonggao_face.png" frame:CGRectMake(140, 8, 29, 29) title:nil tag:TOOLGGBUTTONTAG+3];*/
    /*[self.accessoryView addSubview:barbutton1];
    [self.accessoryView addSubview:barbutton2];
    [self.accessoryView addSubview:barbutton3];
    */
    
    //self.voiceRecord=[[VoiceRecord alloc] init];
	// Do any additional setup after loading the view.
}

-(IBAction)navButtonActon:(UIButton*)sender{
    if (sender!=nil&&sender.tag==NAVGGBUTTONTAG+1) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }else{
        if (!self.caogaoDict) {
            [_delegate success:@{@"ggContent": self.textView.text}];
            return;
        }
        AppDelegate *app=(AppDelegate*)[[UIApplication sharedApplication] delegate];
        if (app.status==NotReachable) {
            [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
            return;
        }
        if (self.textView.text==nil||[self.textView.text isEqualToString:@""]) {
            [Utility customAlertWithMsg:GONGGAOCONTENT andTitle:ALRRTTITLE andDelagate:nil];
            return;
        }
        NSString *url=[NSString stringWithFormat:@"%@/%@",[Utility getServerUrl],ADDGONGGAOACTION];
        NSMutableDictionary *param=[NSMutableDictionary dictionary];
        NSString *preQuanziId=[self.caogaoDict objectForKey:@"preQuanziId"]
        ;
        NSString *userId=[[NSUserDefaults standardUserDefaults] objectForKey:USERID];
        if (preQuanziId!=nil&&![preQuanziId isEqual:@""]) {
            [param setObject:preQuanziId forKey:@"id"];//
        }
        [param setObject:@"1" forKey:@"g.t0"];//供稿类型
        [param setObject:self.textView.text forKey:@"g.g2"];//供稿内容
        [param setObject:userId forKey:@"g.u0"];//供稿人
        [param setObject:[self.caogaoDict objectForKey:@"str1"] forKey:@"g.b0"];//草稿ID
        [param setObject:[self.caogaoDict objectForKey:@"str7"] forKey:@"g.e0"];//圈子ID
        self.request=[[URLRequest alloc] initWithPostURL:url andDelegate:self andPostData:param andFile:nil];
    }
    
}
- (void)requestFinished:(id)context{
    @try{
        NSDictionary *result=[context JSONValue];
        if (result!=nil&&[[result  objectForKey:@"code"] integerValue]==0) {
            if ([[result  objectForKey:@"method"] isEqual:ADDGONGGAOACTION]) {
                if (_delegate&&[_delegate respondsToSelector:@selector(success:)]) {
                    NSDictionary *dict=[result objectForKey:@"data"];
                    if (dict) {
                         [_delegate success:dict];
                    }
                
                }
            }
        }else{
            [Utility customAlertWithMsg:PROCESSERROE andTitle:ALRRTTITLE andDelagate:nil];
        }
    }@catch (NSException *e) {
        [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
    }
}

- (void)requestFailed:(id)context error:(NSString *)error{
    [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
}



- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if (1 == range.length) {//按下回格键
        return YES;
    }
    if ([text isEqualToString:@"\n"]) {//按下return键
         [self navButtonActon:nil];
        //这里隐藏键盘，不做任何处理
        //[textView resignFirstResponder];
        
        return NO;
    }else {
        if ([textView.text length] < 140) {//判断字符个数
            return YES;
        }
    }
    return NO;
}

-(void) topRow{
    if (self.caogaoDict) {
        UIImageView *topBackground=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 44.0f)];
        topBackground.image=[Utility imageNamed:@"cg_bg1.png"];
        topBackground.userInteractionEnabled=YES;
        UILabel *labelTile=[Utility detailTextLabel:CGRectMake(10, 12, 200, 20) andFontSize:15.0];
        labelTile.textColor=UIColorFromRGB(0x000000);
        labelTile.text=[self.caogaoDict objectForKey:@"str2"];
        [topBackground addSubview:labelTile];
        
        UIImageView *imgeLogo=[[UIImageView alloc] initWithFrame:CGRectMake(225, 12, 18, 19)];
        imgeLogo.image=[Utility imageNamed:@"cg_quan.png"];
        [topBackground addSubview:imgeLogo];
        
        UILabel *labelanthor=[Utility detailTextLabel:CGRectMake(249, 15, 70, 14) andFontSize:12];
        labelanthor.textColor=UIColorFromRGB(0x000000);
        labelanthor.text=[self.caogaoDict objectForKey:@"str8"];
        [topBackground addSubview:labelanthor];
        [self.view addSubview:topBackground];
         self.textView=[[UITextView alloc] initWithFrame:CGRectMake(10, 54, 300, 150)];
    }else{
       self.textView=[[UITextView alloc] initWithFrame:CGRectMake(10, 10, 300, 150)];
    }
   
    self.textView.backgroundColor=[UIColor  clearColor];
    self.textView.layer.cornerRadius = 8;//设置那个圆角的有多圆
    self.textView.layer.borderWidth = 1;//设置边框的宽度，当然可以不要
    self.textView.layer.borderColor = [[UIColor blackColor] CGColor];//设置边框的颜色
    self.textView.keyboardType=UIKeyboardAppearanceDefault;
    self.textView.layer.masksToBounds = YES;//设为NO去试试
    self.textView.autocorrectionType=UITextAutocorrectionTypeNo;
    self.textView.returnKeyType=UIReturnKeySend;
    self.textView.textColor=[UIColor blackColor];
    self.textView.font=[UIFont fontWithName:FONT_FAMILY size:15.0];
    self.textView.enablesReturnKeyAutomatically=YES;
    self.textView.delegate=self;
    [self.view addSubview:self.textView];
    [self.textView  becomeFirstResponder];
}
#pragma mark - Text view delegate methods

/*- (BOOL)textViewShouldBeginEditing:(UITextView *)aTextView {
    
    // you can create the accessory view programmatically (in code), or from the storyboard
    if (self.textView.inputAccessoryView == nil) {
        
        self.textView.inputAccessoryView = self.accessoryView;
    }
    
    
    return YES;
}*/

- (BOOL)textViewShouldEndEditing:(UITextView *)aTextView {
    
    [aTextView resignFirstResponder];
    
    return YES;
}

#pragma mark - Responding to keyboard events

//- (void)keyboardWillShow:(NSNotification *)notification {
    /*UIWindow* window = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
    CGRect keyboardFrame = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    keyboardFrame.origin.y+=self.accessoryView.frame.size.height;
      keyboardFrame.size.height-=self.accessoryView.frame.size.height;
    UIView *view=[[UIView alloc] initWithFrame:keyboardFrame];
    view.backgroundColor=[UIColor redColor];
    [window addSubview:view];*/
    /*
     Reduce the size of the text view so that it's not obscured by the keyboard.
     Animate the resize so that it's in sync with the appearance of the keyboard.
     */
    
    //NSDictionary *userInfo = [notification userInfo];
    
    // Get the origin of the keyboard when it's displayed.
  //  NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    
    // Get the top of the keyboard as the y coordinate of its origin in self's view's
    // coordinate system. The bottom of the text view's frame should align with the top
    // of the keyboard's final position.
    //
    /*CGRect keyboardRect = [aValue CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
    
    CGFloat keyboardTop = keyboardRect.origin.y;
    CGRect newTextViewFrame = self.textView.frame;
    newTextViewFrame.size.height = keyboardTop - self.view.bounds.origin.y-self.textView.frame.origin.y;*/
    
    // Get the duration of the animation.
    //NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
   // NSTimeInterval animationDuration;
   // [animationDurationValue getValue:&animationDuration];
    
    // Animate the resize of the text view's frame in sync with the keyboard's appearance.
   /* [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    
    self.textView.frame = newTextViewFrame;
    
    [UIView commitAnimations];*/
//}

/*- (void)keyboardWillHide:(NSNotification *)notification {
    
    NSDictionary *userInfo = [notification userInfo];
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    
    //self.textView.frame = self.view.bounds;
    
    [UIView commitAnimations];
}*/

#pragma mark - Accessory view action
/*
- (IBAction)tappedToolButton:(UIButton *)sender {
    if (sender.tag==TOOLGGBUTTONTAG+1) {
        [self.voiceRecord recordBtnClick:@"1"];
    }else if(sender.tag==TOOLGGBUTTONTAG+2){
       [self.voiceRecord encodeBtnClick:nil];
    }else{
        
        [self.voiceRecord playMp3BtnClick:nil];
    }*/
    
    // When the accessory view button is tapped, add a suitable string to the text view.
    /*NSMutableString *text = [self.textView.text mutableCopy];
    NSRange selectedRange = self.textView.selectedRange;
    
    [text replaceCharactersInRange:selectedRange withString:@"You tapped me.\n"];
    self.textView.text = text;*/
   /* NSLog(@"%d",sender.tag);
}*/


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:nil object:nil];
}

@end
